package salomon.loader 
{
	import flash.display.Bitmap;
	import salomon.event.SimpleModelEvent;
	import salomon.model.SimpleModel;
	import salomon.type.SimpleModelType;
	import salomon.utils.Alert;
	import starling.events.Event;
	import starling.events.EventDispatcher;
	import starling.textures.Texture;
	import starling.textures.TextureAtlas;
	/**
	 * ...
	 * @author Tiago Salomon
	 */
	public class TextureLoader extends EventDispatcher
	{
		private var _modelXml		: SimpleModel;
		private var _modelSprite	: SimpleModel;
		private var _texture		: Texture;
		private var _atlas			: TextureAtlas;
		private var _spritePath		: String;
		private var _name			: String;
		private var _xmlPath		: String;
		
		public function TextureLoader(name:String, xmlPath:String, spritePath:String) 
		{			
			this._xmlPath = xmlPath;
			this._name 		 = name;
			this._spritePath = spritePath;
			
			_modelXml = new SimpleModel("TextureModelXML-"+_name, SimpleModelType.DATA, false);
			_modelXml.addEventListener(SimpleModelEvent.COMPLETE, onXmlComplete);			
		}
		
		public function loadTexture():void 
		{
			_modelXml.load(_xmlPath);
		}
		
		private function onXmlComplete(e:SimpleModelEvent):void 
		{	
			_modelSprite = new SimpleModel("TextureModelSPRITE-"+_name, SimpleModelType.DISPLAY, false);
			_modelSprite.load(_spritePath);
			_modelSprite.addEventListener(SimpleModelEvent.COMPLETE, onSpriteSheetComplete);
		}
		
		private function onSpriteSheetComplete(e:SimpleModelEvent):void 
		{			
			_texture = Texture.fromBitmap(Bitmap(_modelSprite.data.content));
			_atlas = new TextureAtlas(_texture, XML(_modelXml.data.content));
			
			this.dispatchEvent(new Event(Event.ADDED));
		}
		
		public function get atlas():TextureAtlas 
		{
			return _atlas;
		}
		
		public function get name():String 
		{
			return _name;
		}
		
	}

}